<template>
  <div class="teach">
    <my-tabs :tab-list="tabList"></my-tabs>
    <el-button size="mini" type="primary" @click="handleAddMenu(course_id, 0)">新建</el-button>
    <el-table
      class="teach-table"
      :data="sectionList"
      row-key="id"
      :show-header="false"
      :tree-props="treeProps"
      size="mini"
    >
      <el-table-column>
        <template slot-scope="scope">
          {{ scope.row.title }}
          <!-- <template v-if="scope.row.level == sectionLevel">
            <el-tag type="warning" size="mini" v-if="scope.row.status == 0">审核未通过</el-tag>
            <el-tag type="success" size="mini" v-else-if="scope.row.status == 1">审核通过</el-tag>
            <el-tag type="info" size="mini" v-else-if="scope.row.status == 2 || scope.row.status == 3">待审核</el-tag>
          </template> -->
        </template>
      </el-table-column>
      <el-table-column width="260">
        <template slot-scope="scope">
          <el-row type="flex" justify="end" align="middle">
            <template v-if="scope.row.level == sectionLevel && $util.isDef(scope.row.live_info)">
              <!-- 925即将直播 999直播中 -->
              <template
                v-if="scope.row.live_info.status == 957 || scope.row.live_info.status == 999"
              >
                <el-button size="mini" type="text" @click="handleStart(scope)">去上课</el-button>
                <el-divider direction="vertical"></el-divider>
              </template>
            </template>

            <el-button size="mini" type="text" @click="handleEdit(scope)">编辑</el-button>
            <template v-if="scope.row.course_sec_level > scope.row.level">
              <el-divider direction="vertical"></el-divider>
              <el-button size="mini" type="text" @click="handleAdd(scope)">添加</el-button>
            </template>
            <el-divider direction="vertical"></el-divider>
            <el-button size="mini" type="text" @click="handleDelete(scope)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import MyTabs from '../../../../components/myTab.vue'
import Base64 from '@/utils/base64.js'
export default {
  components: {
    MyTabs
  },
  inject: ['reload'],
  data() {
    return {
      tabList: [
        {
          title: '课时管理'
        }
      ],
      course_id: this.$route.params.id,
      treeProps: { children: 'child', hasChildren: 'hasChildren' },
      sectionList: [],
      sectionLevel: 0
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.info,
      token: state => state.user.token
    })
  },
  mounted() {
    this.handleSectionTree()
    this.handleSectionLevel()
  },
  methods: {
    // 获取课时树
    handleSectionTree() {
      this.$api.getTeacherCourseSectionTree(this.course_id, res => {
        this.sectionList = res.data
      })
    },
    // 课程目录层级
    handleSectionLevel() {
      this.$api.getTeacherCourseSectionLevel(this.course_id, res => {
        this.sectionLevel = res.data
      })
    },
    // 新建章节
    handleAddMenu(id, pid) {
      if (this.sectionLevel == 1) {
        // 添加课时
        this.$router.push({
          path: `/my/classes/teach/live/small/${this.course_id}/create`,
          query: {
            id: pid
          }
        })
      } else {
        this.$messageBox
          .prompt('', {
            title: '添加章节',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputType: 'text',
            inputValue: '',
            inputPattern: /\S/,
            inputErrorMessage: '章节名称不能为空',
            inputPlaceholder: '章节名称',
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: true
          })
          .then(({ value }) => {
            this.$api.createTeacherCourseSectionMenu(
              id,
              pid,
              {
                title: value
              },
              res => {
                this.$message.success(res.msg, res => {
                  this.reload()
                })
              },
              error => {
                this.$message.error(error.msg)
              }
            )
          })
          .catch(() => {})
      }
    },
    // 添加
    handleAdd(scope) {
      if (scope.row.course_sec_level - 1 == scope.row.level) {
        // 添加课时
        this.$router.push({
          path: `/my/classes/teach/live/small/${this.course_id}/create`,
          query: {
            id: scope.row.id
          }
        })
      } else {
        // 添加章节
        this.handleAddMenu(this.course_id, scope.row.id)
      }
    },
    // 编辑
    handleEdit(scope) {
      if (scope.row.is_last == 0) {
        // 编辑章节
        this.$messageBox
          .prompt('', {
            title: '编辑章节',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputType: 'text',
            inputValue: scope.row.title,
            inputPattern: /\S/,
            inputErrorMessage: '章节名称不能为空',
            inputPlaceholder: '章节名称',
            closeOnClickModal: false,
            closeOnPressEscape: false,
            showClose: true
          })
          .then(({ value }) => {
            this.$api.updateTeacherCourseSectionMenu(
              this.course_id,
              scope.row.id,
              {
                title: value
              },
              res => {
                this.$message.success(res.msg, res => {
                  this.reload()
                })
              },
              error => {
                this.$message.error(error.msg)
              }
            )
          })
          .catch(() => {})
      } else {
        // 编辑课时
        this.$router.push({
          path: `/my/classes/teach/live/small/${this.course_id}/edit`,
          query: {
            id: scope.row.id
          }
        })
      }
    },
    // 删除
    handleDelete(scope) {
      this.$messageBox
        .confirm('确定删除吗？')
        .then(() => {
          this.$api.deleteTeacherCourseSectionDelete(
            this.course_id,
            scope.row.id,
            res => {
              this.$message.success(res.msg, res => {
                this.handleSectionTree()
              })
            },
            err => {
              this.$message.error(err.msg)
            }
          )
        })
        .catch(() => {})
    },
    // 去上课
    handleStart(scope) {
      if (scope.row.live_provider === 2) {
        // 声网直播
        this.$store.commit('course/setCurrentPlayItem', {
          id: scope.row.id
        })

        let agoraName = {
          1: 'agora-big-class',
          2: 'agora-small-class',
          3: 'agora-one-to-one'
        }
        let agoraRoom = agoraName[scope.row.course_live_type]
        this.$router.push({
          name: agoraRoom
        })
      } else if (scope.row.live_provider === 3) {
        // cc 直播
        let item = scope.row.live_data
        if (this.$util.isEmpty(item)) {
          // 新建直播间
          this.createCcSmllClass({
            id: scope.row.id
          })
        } else {
          // 进入直播间
          this.enterCcLive({
            cc_room_id: item.cc_room_id,
            cc_userid: item.cc_userid,
            password: '123456'
          })
        }
      }
    },
    // 创建cc小班课
    createCcSmllClass(data) {
      let params = {
        section_id: data.id, // 课时ID
        publisherpass: '123456' // 讲师密码
      }
      this.$api.setLiveCcktRoomCreate(params, res => {
        const { data } = res
        this.enterCcLive({
          cc_room_id: data.cc_room_id,
          cc_userid: data.cc_userid,
          password: '123456'
        })
        // 初始化页面数据
        this.handleSectionTree()
      })
    },
    // 进入cc直播
    enterCcLive(item) {
      const user = this.userInfo
      const params = {
        roomid: item.cc_room_id,
        userid: item.cc_userid,
        username: user.nick_name,
        password: item.password,
        autoLogin: true,
        role: 'presenter',
        template: 32
      }
      const link = `https://class.csslcloud.net/hdclass/#/presenter?${this.params(params)}`
      this.$router.push({
        name: 'cc-live',
        query: {
          view: Base64.encode(link)
        }
      })
    },
    params(obj) {
      let result = ''
      let item
      for (item in obj) {
        if (obj[item] && String(obj[item])) {
          result += `&${item}=${obj[item]}`
        }
      }
      if (result) {
        result = result.slice(1)
      }
      return result
    }
  }
}
</script>
<style lang="scss" scoped>
.teach-table {
  margin-top: 10px;
  .el-tag {
    margin-left: 10px;
  }
}
</style>
